const XLSX = require('xlsx');
const fs = require('fs');
const path = require('path');

function readJsonWithComments(filePath) {
    try {
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const filteredContent = fileContent.replace(/\/\/.*$/gm, '');
        const jsonData = JSON.parse(filteredContent);
        return jsonData;
    } catch (error) {
        console.error(`读取或解析 JSON 文件时出错: ${error.message}`);
        return null;
    }
}

function jsonFilesToExcel(folderPath, excelFilePath) {
    const nonUniAppJsonFiles = fs.readdirSync(folderPath).filter(file => {
        return !file.startsWith('uni-app') && path.extname(file) === '.json';
    });

    const uniAppJsonFiles = fs.readdirSync(folderPath).filter(file => {
        return file.startsWith('uni-app') && path.extname(file) === '.json';
    });

    // 处理非 uni-app 的 JSON 文件
    const allNonUniAppData = {};
    let zhNonUniAppData = null;
    nonUniAppJsonFiles.forEach(file => {
        const filePath = path.join(folderPath, file);
        const data = readJsonWithComments(filePath);
        const lang = path.basename(file, '.json');
        if (lang === 'zh') {
            zhNonUniAppData = data;
        }
        allNonUniAppData[lang] = data;
    });

    if (!zhNonUniAppData) {
        console.error('未找到 zh.json 文件，请检查文件夹内容。');
        return;
    }

    const nonUniAppKeys = Object.keys(zhNonUniAppData);
    const otherNonUniAppLangs = nonUniAppJsonFiles.map(file => path.basename(file, '.json')).filter(lang => lang!== 'zh');
    const nonUniAppHeaders = ['id', '描述', 'zh', ...otherNonUniAppLangs];
    const nonUniAppRows = nonUniAppKeys.map(key => {
        const row = [key, ''];
        nonUniAppHeaders.slice(2).forEach(lang => {
            row.push(allNonUniAppData[lang][key] || '');
        });
        return row;
    });
    nonUniAppRows.unshift(nonUniAppHeaders);

    // 处理 uni-app 的 JSON 文件
    const allUniAppData = {};
    let zhUniAppData = null;
    uniAppJsonFiles.forEach(file => {
        const filePath = path.join(folderPath, file);
        const data = readJsonWithComments(filePath);
        const parts = path.basename(file, '.json').split('.');
        const lang = parts.length > 1? parts[1] : path.basename(file, '.json');
        if (lang === 'zh') {
            zhUniAppData = data;
        }
        allUniAppData[lang] = data;
    });

    if (!zhUniAppData) {
        console.error('未找到 uni-app 相关的 zh.json 文件，请检查文件夹内容。');
        return;
    }

    const uniAppHeaders = ['id', '描述', 'zh', ...uniAppJsonFiles.map(file => {
        const parts = path.basename(file, '.json').split('.');
        return parts.length > 1? parts[1] : path.basename(file, '.json');
    }).filter(lang => lang!== 'zh')];

    const uniAppRows = [];
    for (const firstLevelKey in zhUniAppData) {
        const firstLevelData = zhUniAppData[firstLevelKey];
        for (const secondLevelKey in firstLevelData) {
            const row = [secondLevelKey, firstLevelKey];
            uniAppHeaders.slice(2).forEach(lang => {
                const langData = allUniAppData[lang];
                if (langData && langData[firstLevelKey]) {
                    row.push(langData[firstLevelKey][secondLevelKey] || '');
                } else {
                    row.push('');
                }
            });
            uniAppRows.push(row);
        }
    }
    uniAppRows.unshift(uniAppHeaders);

    // 创建工作簿
    const wb = XLSX.utils.book_new();

    // 创建第一个工作表
    const nonUniAppWs = XLSX.utils.aoa_to_sheet(nonUniAppRows);
    XLSX.utils.book_append_sheet(wb, nonUniAppWs, 'Sheet1');

    // 创建第二个工作表
    const uniAppWs = XLSX.utils.aoa_to_sheet(uniAppRows);
    XLSX.utils.book_append_sheet(wb, uniAppWs, 'uni-app');

    // 保存为 Excel 文件
    XLSX.writeFile(wb, excelFilePath);
    console.log(`JSON 文件已成功转换为 Excel 文件：${excelFilePath}`);
}

// 使用示例
const folderPath = path.join(__dirname, '../locale/');
const excelFilePath = path.join(__dirname, '../locale/智源APP多语言文件.xlsx');
jsonFilesToExcel(folderPath, excelFilePath);
